/**
 * 
 */
$(document).ready(function () {
	/**
	 * Redirige l'utilisateur si il est déjà connectée
	 */
	if(auth != null && auth.connected == false) {
		window.location.href = "/index.html";
	}
	
	refreshTable();
	
	$("#volList").delegate(".deleteVol", "click", function() {
		var idBtn = $(this).attr("id");
		$.ajax({
			url: 'vol' + '?' + $.param({"cmd": "deleteVolQueue", "id": $(this).attr("id")}),
            type: "DELETE",
        }).done(function(data, textStatus, jqXHR) {
        	setAlertMessage('Succès!','Vol supprimé','success');
        	$("#" + idBtn).closest("tr").remove();
        }).fail(function(jqXHR, textStatus, errorThrown) {
        	setAlertMessage('Erreur!',errorThrown+ ' (' + textStatus +')','danger');
        });
		return false;
	});
	
	$("#btnAddVol").click(function() {
		var formData = $("#addVol-form").serializeArray();
		formData.push({name:"cmd",value:"addVolQueue"});
		$.ajax(
            "vol",{
            type: "POST",
            data: formData,
        }).done(function(data, textStatus, jqXHR) {
        	setAlertMessage('Succès!','Vol ajouté','success');
        }).fail(function(jqXHR, textStatus, errorThrown) {
        	setAlertMessage('Erreur!',errorThrown+ ' (' + textStatus +')','danger');
        });
		return false;
	});	
	
	$("#btnRefresh").click(refreshTable);
	
	function refreshTable() {
		$.ajax('vol',{
			type:'GET',
			dataType: "json",
			data: {
				cmd:'listeVol',
	        },
		}).done(function(data, testStatus, jqXHR){
			$("#volList").empty();
			for(var vol in data)
			{
				$("#volList").append(
				"<tr class=\"data\"><td>" +
				data[vol].date + 
				"</td><td>" + 
				data[vol].leavingFrom +
				"</td><td>" + 
				data[vol].goingTo +
				"</td><td>" +
				data[vol].flightDuration +
				"</td><td>" +
				data[vol].availableSeats +
				"</td><td>" +
				data[vol].price +
				"</td><td>" +
				"<a class=\"btn btn-primary btn-block deleteVol\" href=\"\" " +
				"id=\"" +
				data[vol].id +
				"\">Supprimer</a>" +
				"</td></tr>"		
				);
			};
		}).fail(function(jqXHR, textStatus, errorThrown) {
	    	setAlertMessage('Erreur!',errorThrown+ ' (' + textStatus +')','danger');
	    });
	}
});